/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.group;

import com.bytedance.scene.utlity.HiLogUtil;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.rpc.MessageParcel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

public final class SceneAsyncLayoutInflater {
    private static final String TAG = "AsyncLayoutInflater";

    LayoutScatter mInflater;
    EventHandler mHandler;
    InflateThread mInflateThread;

    public SceneAsyncLayoutInflater(Context sceneContext) {
        mInflater = LayoutScatter.getInstance(sceneContext);
        mHandler = new SceneAsyncEventHandle(EventRunner.getMainEventRunner());
        mInflateThread = InflateThread.getInstance();
    }

    public void inflate(int resid, ComponentContainer parent,
                        OnInflateFinishedListener callback) {
        if (callback == null) {
            throw new NullPointerException("callback argument may not be null!");
        }
        InflateRequest request = mInflateThread.obtainRequest();
        request.inflater = this;
        request.resid = resid;
        request.parent = parent;
        request.callback = callback;
        mInflateThread.enqueue(request);
    }


    class SceneAsyncEventHandle extends EventHandler {
        public SceneAsyncEventHandle(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            InflateRequest request = (InflateRequest) event.object;
            if (request.view == null) {
                request.view = mInflater.parse(request.resid, request.parent, false);
            }
            request.callback.onInflateFinished(
                    request.view, request.resid, request.parent);
            mInflateThread.releaseRequest(request);
        }
    }

    public interface OnInflateFinishedListener {
        void onInflateFinished(Component view, int resid,
                               ComponentContainer parent);
    }

    private static class InflateRequest {
        SceneAsyncLayoutInflater inflater;
        ComponentContainer parent;
        int resid;
        Component view;
        OnInflateFinishedListener callback;

        InflateRequest() {
        }
    }

    private static class

    InflateThread extends Thread {
        private static final InflateThread sInstance;

        static {
            sInstance = new InflateThread();
            sInstance.start();
        }

        public static InflateThread getInstance() {
            return sInstance;
        }

        private ArrayBlockingQueue<InflateRequest> mQueue = new ArrayBlockingQueue<>(10);
        private HashMap<String, InflateRequest> mRequestPool = new HashMap(10);

        // Extracted to its own method to ensure locals have a constrained liveness
        // scope by the GC. This is needed to avoid keeping previous request references
        // alive for an indeterminate amount of time, see b/33158143 for details
        public void runInner() {
            InflateRequest request;
            try {
                request = mQueue.take();
            } catch (InterruptedException ex) {
                // Odd, just continue
                HiLogUtil.warn(TAG, ex.getMessage());
                Thread.currentThread().interrupt();
                return;
            }

            try {
                request.view = request.inflater.mInflater.parse(
                        request.resid, request.parent, false);
            } catch (RuntimeException ex) {
                // Probably a Looper failure, retry on the UI thread
                HiLogUtil.warn(TAG, "Failed to inflate resource in the background! Retrying on the UI"
                        + " thread", ex);
            }
            InnerEvent event = InnerEvent.get();
            event.eventId = 0;
            event.object = request;
            request.inflater.mHandler.sendEvent(event);
        }

        @Override
        public void run() {
            while (true) {
                runInner();
            }
        }

        public InflateRequest obtainRequest() {
            InflateRequest obj = mRequestPool.get("RequestKey");
            if (obj == null) {
                obj = new InflateRequest();
            }
            return obj;
        }

        public void releaseRequest(InflateRequest obj) {
            obj.callback = null;
            obj.inflater = null;
            obj.parent = null;
            obj.resid = 0;
            obj.view = null;
            mRequestPool.put("RequestKey", obj);
        }

        public void enqueue(InflateRequest request) {
            try {
                mQueue.put(request);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(
                        "Failed to enqueue async inflate request", e);
            }
        }
    }
}